#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * There is a small error, the result should be 871198282 but this returns 871188727
 */

int compare (const void* a, const void* b)
{
	return strcmp(*(char**)a, *(char**)b);
}

int main ()
{
	int result = 0, word = 1, i = 0;
	char** names = (char**) malloc(5200 * sizeof(void*));

	// Read text file
	{
		names[0] = 0;
		names[word] = (char*) malloc(12);
		FILE* file = fopen("names.txt", "r");
		while (!feof(file))
		{
			char c = fgetc(file);

			if (c == '"')
				continue;

			if (c == ',')
			{
				names[word][i] = 0;
				i = 0;
				word++;
				names[word] = (char*) malloc(12);
			}
			else names[word][i++] = c;
		}
		fclose (file);
		names[word+1] = 0;
	}

	// Sort
	qsort(names+1, word, sizeof(char*), compare);
	// for (int i = 1; names[i]; i++) puts(names[i]);

	// GO!
	for (i = 1; names[i]; i++)
	{
		int score = 0, j;
		for (j = 0; names[i][j]; j++)
			score += names[i][j] - '@';

		result += score * i;
		// printf("%u: %s\t%u\t%u\n", i, names[i], score, result);
	}

	printf("Result: %u\n", result);
	return 0;
}
